var fs = require( 'fs' );
var app = require('express')();
var https        = require('https');
var messages = [];
var receivers = [];
var projector;
var options = {
  key: fs.readFileSync('./cakey.pem'),
  cert: fs.readFileSync('./cacert.pem'),
      requestCert: false,
    rejectUnauthorized: false
};
var server = https.createServer(options,app);
server.listen(3000);

var io = require('socket.io').listen(server);

io.sockets.on('connection',function (socket) {
    console.log('ok_connection')
});
var projector2 = io
  .of('/projector')
  .on('connection', function (socket) {
console.log('projector connection initiating.');

    if (projector) {
      console.log('closing existing projector. setting messages to 0');
      projector.disconnect();
      messages.length = 0;
    }

    projector = socket;

    messages.push(JSON.stringify({ clear: true }));

    receivers.forEach(function(socket) {
      socket.emit('receiver',messages[0]);
    });


    socket.on('projector',function(data) {
      console.log('message received. now at ' + messages.length + ' . sending to ' + receivers.length);
      receivers.forEach(function(receiver) {
        receiver.emit('receiver',data);
      });

      messages.push(data);
    });

    socket.on('disconnect', function() {
      console.log('projector closing, clearing messages');
      messages.length = 0;
      receivers.forEach(function(socket) {
        socket.emit('receiver',JSON.stringify({ clear: true }));
      });

      projector = undefined;
    });
  });

app.get("/", function(request, response){
    response.sendfile('views/test.html');
})